<template>
	<view class="page-container">
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="title">我的</view>
		</view>

		<view class="user-info">
					<button 
						class="avatar-button" 
						open-type="chooseAvatar" 
						@chooseavatar="onChooseAvatar"
					>
						<image 
							class="avatar" 
							:src="userInfo?.avatar" 
							mode="aspectFill" 
						/>
					</button>
					<!-- Added click handler and dynamic classes for nickname -->
					<view class="nickname-container" @tap="startEditingNickname">
						<text v-if="!isEditingNickname" class="nickname">{{ userInfo?.username || '未登录' }}</text>
						<input
							v-else
							class="nickname-input"
							type="text"
							v-model="tempNickname"
							@blur="saveNickname"
							@confirm="saveNickname"
							auto-focus
						/>
					</view>
					<text class="id">豆包号: {{ userInfo?.doubao_id || '--' }}</text>
					<text class="count">{{ userInfo?.smart_device_count || 0 }}个智能体</text>
					<button class="edit-btn"></button>
				</view>

		<view class="content">
			<view class="tabs">
				<view class="tab-item" :class="{ active: currentTab === 'ai' }" @tap="switchTab('ai')">
					<text class="tab-text">智能体</text>
				</view>
				<view class="tab-item" :class="{ active: currentTab === 'created' }" @tap="switchTab('created')">
					<text class="tab-text">创建</text>
				</view>
			</view>

			<scroll-view class="device-list" scroll-y>
				<AICard v-for="device in deviceList" :key="device.id" :id="device.id" :avatar="device.icon"
					:name="device.name" :description="device.description" :chat-count="device.chatCount"
					:is-collected="device.isCollected" @click="gotoChat" @collect="handleCollect" />
			</scroll-view>
		</view>

		<view class="tab-bar">
			<view v-for="(tab, index) in bottomTabs" :key="index" class="tab-item"
				:class="{ active: currentBottomTab === index }" @tap="switchBottomTab(index)">
				<text class="iconfont" :class="tab.icon" />
				<text class="label">{{ tab.text }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore, useDeviceStore } from '@/stores'
import { system } from '@/utils'

const userStore = useUserStore()
const deviceStore = useDeviceStore()
const statusBarHeight = system.getStatusBarHeight()

// Add new reactive variables for nickname editing
const isEditingNickname = ref(false)
const tempNickname = ref('')

// Start editing nickname
const startEditingNickname = () => {
  tempNickname.value = userInfo.value.username
  isEditingNickname.value = true
}

// Save nickname
const saveNickname = async () => {
  if (!tempNickname.value || tempNickname.value === userInfo.value.username) {
    isEditingNickname.value = false
    return
  }

  try {
    // Update nickname
    await userStore.updateNicknameAndAvatar(
      tempNickname.value,  // new nickname
      null  // don't update avatar
    )
	
    // Refresh user info
    await userStore.getUserInfo()
    uni.showToast({
      title: '更新成功',
      icon: 'success'
    })
	
  } catch (error) {
    console.error('更新昵称失败:', error)
    uni.showToast({
      title: error.message || '更新昵称失败',
      icon: 'none'
    })
  } finally {
    isEditingNickname.value = false
  }
}

// 在 my.vue 中
const onChooseAvatar = async (e) => {
  const { avatarUrl } = e.detail
  console.log('用户选择的头像:', avatarUrl)
  
  try {
    // 先将临时文件上传到服务器
    const uploadRes = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: 'https://szxhdkj.com/api/device/upload/icon',
        filePath: avatarUrl,
        name: 'file',
        header: {
          'Authorization': uni.getStorageSync('token'),
          'User-Id': uni.getStorageSync('userId')
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            const result = JSON.parse(uploadRes.data)
            if (result.code === 200 && result.data) {
              resolve(result.data)
            } else {
              reject(new Error(result.message || '上传失败'))
            }
          } else {
            reject(new Error('上传失败'))
          }
        },
        fail: reject
      })
    })

    console.log('头像上传成功，URL:', uploadRes)
    
    // 更新用户信息到后端 - 修改这里，只传入新的头像URL
    await userStore.updateNicknameAndAvatar(
      null,  // 不更新用户名
      uploadRes  // 只更新头像
    )
    
    // 刷新用户信息
    await userStore.getUserInfo()
    
    uni.showToast({
      title: '更新成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('更新头像失败:', error)
    uni.showToast({
      title: error.message || '更新头像失败',
      icon: 'none'
    })
  }
}

// 上传文件到 Minio
const uploadFile = (tempFilePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'https://szxhdkj.com/api/device/upload/icon',
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Authorization': uni.getStorageSync('token'),
        'User-Id': uni.getStorageSync('userId')
      },
      success: (uploadRes) => {
        if (uploadRes.statusCode === 200) {
          const result = JSON.parse(uploadRes.data)
          if (result.code === 200 && result.data) {
            resolve(result.data)
          } else {
            reject(new Error(result.message || '上传失败'))
          }
        } else {
          reject(new Error('上传失败'))
        }
      },
      fail: (error) => {
        console.error('上传失败:', error)
        reject(error)
      }
    })
  })
}

// 用户信息计算属性
const userInfo = computed(() => {
  const user = userStore.userInfo
  return {
    username: user?.username || '',
    doubao_id: user?.doubaoId || '',
    avatar: user?.avatar || '',
    smart_device_count: deviceList.value?.length || 0
  }
})

// 设备列表数据
const deviceList = computed(() => {
  if (currentTab.value === 'ai') {
    return deviceStore.privateDevices || []
  } else if (currentTab.value === 'created') {
    return deviceStore.privateDevices?.filter(device =>
      device.creatorId === userStore.userInfo?.id ||
      device.creatorName === userStore.userInfo?.username
    ) || []
  }
  return []
})

// Tab状态
const currentTab = ref('ai')
const currentBottomTab = ref(4)

// 底部标签配置
const bottomTabs = [
  { text: '对话', icon: 'icon-message' },
  { text: '发现', icon: 'icon-search' },
  { text: '创建', icon: 'icon-add' },
  { text: '通知', icon: 'icon-notification' },
  { text: '我的', icon: 'icon-user' }
]

// 数据加载
const loadData = async () => {
  try {
    if (currentTab.value === 'ai' || currentTab.value === 'created') {
      await deviceStore.loadPrivateDevices()
    } else {
      await deviceStore.loadCollectedDevices()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

// Tab切换
const switchTab = async (tab) => {
  currentTab.value = tab
  await loadData()
}

// 底部导航切换
const switchBottomTab = (index) => {
  uni.switchTab({
    url: [
      '/pages/index/index',
      '/pages/discover/discover',
      '/pages/create/create',
      '/pages/notification/notification',
      '/pages/my/my'
    ][index]
  })
}

// 聊天跳转
const gotoChat = (deviceId) => {
  uni.navigateTo({
    url: `/pages/chat/chat?id=${deviceId}`
  })
}

// 收藏处理
const handleCollect = async (deviceId) => {
  await deviceStore.toggleCollect(deviceId)
  await loadData()
}

// 初始化
onMounted(async () => {
  try {
    if (!userStore.userInfo) {
      await userStore.getUserInfo()
    }
    await loadData()
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style lang="scss">
.page-container {
  height: 100vh;
  background: #F5F5F5;

  .nav-bar {
    height: 88rpx;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    border-bottom: 1px solid #f5f5f5;

    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .user-info {
    height: 520rpx;
    background: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;

    .avatar-button {
      padding: 0;
      width: 180rpx !important;
      height: 180rpx !important;
      margin-bottom: 24rpx;
      background: none;
      border: none;

      &::after {
        border: none;
      }
    }

    .avatar {
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
    }

    .nickname-container {
          margin-bottom: 12rpx;
        }
    
        .nickname {
          font-size: 40rpx;
          font-weight: 500;
        }
    
        .nickname-input {
          font-size: 40rpx;
          font-weight: 500;
          text-align: center;
          width: 400rpx;
          padding: 4rpx 8rpx;
          border-bottom: 2rpx solid #007AFF;
        }

    .id {
      color: #999;
      font-size: 28rpx;
      margin-bottom: 8rpx;
    }

    .count {
      color: #666;
      font-size: 26rpx;
      margin-bottom: 36rpx;
    }
  }

  .content {
    background: #fff;
    flex: 1;

    .tabs {
      height: 100rpx;
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #F5F5F5;

      .tab-item {
        flex: 1;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .tab-text {
          font-size: 32rpx;
          color: #999;
          position: relative;
          padding: 20rpx 0;
        }

        &.active .tab-text {
          color: #333;
          font-weight: 500;

          &::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
            width: 48rpx;
            height: 4rpx;
            background: #007AFF;
          }
        }
      }
    }

    .device-list {
      padding: 0;
    }
  }

  .tab-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 110rpx;
    background: #fff;
    display: flex;
    align-items: center;
    border-top: 1rpx solid #eee;
    padding-bottom: env(safe-area-inset-bottom);

    .tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #999;

      .iconfont {
        font-size: 48rpx;
        margin-bottom: 6rpx;
      }

      .label {
        font-size: 24rpx;
      }

      &.active {
        color: #007AFF;
      }
    }
  }
}
</style>